<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" type="text/css" href="../../css/api.css" />
  <link rel="stylesheet" type="text/css" href="../../css/kaifang.css" />
</head>

<body>
  <div id="app" v-cloak>
    <!-- 患者信息 -->
    <div class="topInfo">
      {{patients.name}}
      <span>
        <span v-if="patients.sex == 1">男</span>
        <span v-if="patients.sex == 2">女</span>
        <span v-if="patients.age">{{patients.age}}岁</span>
      </span>
      <!-- <span class="btn">调用常用方</span> -->
    </div>
    <!-- 开方 -->
    <div class="kaifang">
      <div class="zhenduan">
        <div class="title">诊断</div>
        <div>辨病：<input type="text" v-model="forms.diseases"></div>
        <div>辨证：<input type="text" v-model="forms.dialectical"></div>
      </div>
      <p class="title">开方</p>
      <div class="pharmacy">
        <layerselect label="药房药态:" placeholder="请选择药房" :options="iOptions.storeOptions"
          :dosagelist="iOptions.dosageformOptions" @choosestore="chooseStore" @changedosage="listStoreByDosage"
          @openwin="openWinStore" />
      </div>
      <div class="clear top-line"></div>
      <!-- 药材选择好了 -->
      <div class="RP_main" v-if="treatmentDrugs">
        <div class="RP_main_item" v-for="item in treatmentDrugs">{{item.name}}{{item.quantity}}{{item.unit}}</div>
      </div>

      <!-- RP -->
      <div class="RP" v-show="forms.storeId" v-if="treatmentDrugs.length == 0">
        <p class="title">RP :</p>
        <div class="add_btn" @click="openWinDrugs(0)">添加药材</div>
      </div>
      <div class="RP" v-show="forms.storeId" v-else>
        <p class="title">RP :</p>
        <div class="add_btn" @click="openWinDrugs(1)">编辑药材</div>
      </div>
    </div>


    <!-- 用法 -->
    <div class="placeholder_div"></div>
    <div class="useing">

      <p class="title">用法用量</p>
      <div class="useing_detail">
        <span>每日药量:</span>
        <input type="Number" v-model="forms.dailyDose"><span>帖</span>
      </div>
      <div class="useing_detail">
        <selectbox label="给药频率:" default="请选择给药频率" placeholder="请选择给药频率" :list="iOptions.frequencyOptions"
          @choosefunc="chooseFrequencyFn" />
      </div>
      <div class="useing_method">
        <selectbox label="给药途径:" default="内服" placeholder="请选择给药途径" :list="iOptions.routeOptions"
          @choosefunc="chooseRouteFn" />
      </div>
      <div class="useing_detail">
        <span>开药量:</span>
        <input type="Number" v-model="forms.quantity"><span>帖</span>，
      </div>
      <!-- 医嘱 -->
      <div class="yizhu">
        医嘱：
        <input type="text" readonly class="openwin yizhu" @click="openWinAdvice" v-model="forms.medicalAdvice"
          :data-content="forms.medicalAdvice" placeholder="请填写相关医嘱">
      </div>
    </div>
    <div class="placeholder_div"></div>


    <!-- 方案设置 -->
    <div class="fanganshezhi">
      <p class="title">方案设置</p>
      <div class="fanganshezhi_item">
        <inputselect label="诊费" default="免费" placeholder="请选择诊费,也可自定义输入" :options="iOptions.treatmentCost"
          @choosefunc="chooseBillingFun" />
      </div>

      <div class="fanganshezhi_item">
        <!-- <selectbox label="服务费:" :default="forms.serviceMoney" placeholder="请选择服务费" :list="iOptions.serviceOptions"
          @choosefunc="chooseServiceFn" /> -->
        服务费 <span style="float: right;">￥{{forms.serviceMoney}}元</span>
      </div>

      <div class="fanganshezhi_item">
        <selectbox label="购药前处方可见:" default="可见" placeholder="请选择" :list="iOptions.visibleOptions"
          @choosefunc="chooseVisibleFn" />
      </div>
    </div>
    <div class="placeholder_div"></div>


    <!-- 总计 -->
    <div class="total">
      <p class="title" v-if="forms.totalMoney">总计<span>￥{{forms.totalMoney}}</span></p>
      <div class="item">诊金 <span>￥{{forms.billingMoney}}</span></div>
      <div class="item">服务费总计 <span>{{forms.serviceMoney}} x {{forms.quantity}} = ￥{{forms.totalServiceMoney}}</span>
      </div>
      <div class="item">总药价 <span>{{toThreeDecimal(forms.drugMoney)}} x {{forms.quantity}} =
          ￥{{forms.totalDrugMoney}}</span>
      </div>
      <p>*患者不展示治疗服务费，治疗服务费直接计入在药费总额中</p>
      <p>*不含运费、代煎费，药费依据购药时实际选择的药房而定</p>
    </div>
    <div class="placeholder_div"></div>
    <!-- 确认选择患者按钮 -->
    <div class="order_btn p_hide" @click="confirmFn">确认开方</div>
  </div>
  <script src="../../script/set_root.js"></script>

  <script type="text/javascript" src="../../script/api.js"></script>
  <script type="text/javascript" src="../../script/hb.js"></script>
  <script type="text/javascript" src="../../script/vue.js"></script>
  <script type="text/javascript" src="../../script/httpVueLoader.js"></script>
  <script type="text/javascript">
    apiready = function () {
      initVue();
      // alert(JSON.stringify(api.pageParam))
    };

    function initVue() {
      window.kfVue = new Vue({
        el: '#app',
        components: {
          "selectbox": httpVueLoader(HTTP_DOMAIN + 'components/select.vue'),
          "inputselect": httpVueLoader(HTTP_DOMAIN + 'components/input-select.vue'),
          "layerselect": httpVueLoader(HTTP_DOMAIN + 'components/layer-select.vue')
        },
        data: {
          //目标数据(医生数据)
          doctors: {
            doctorName: "",
            doctorUserId: 0,
            doctorAvatar: "",
            doctorJobtitle: ""
          },
          //（患者数据）
          users: {
            userId: 0,
            avatar: ""
          },
          //就诊人数据
          patients: {
            patientId: 0,
            userId: 0,
            sex: 1,
            age: 0,
            name: "",
            phone: ""
          },
          //下拉框选项
          iOptions: {
            routeOptions: [{
              "text": "内服",
              "value": 1
            }, {
              "text": "外用",
              "value": 2
            }], //用药方法
            //给药频率
            frequencyOptions: [{
              "text": "一贴两次",
              "value": 2
            }, {
              "text": "一贴一次",
              "value": 1
            }],
            treatmentCost: [{
              "value": "0",
              "text": "免费"
            }, {
              "value": "50",
              "text": "￥50元"
            },{
              "value": "100",
              "text": "￥100元"
            }, {
              "value": "200",
              "text": "￥200元"
            }, {
              "value": "0",
              "text": "自定义"
            }],
            serviceOptions: [{
              "value": "0",
              "text": "免费"
            }],
            visibleOptions: [{
              "value": "1",
              "text": "可见"
            }, {
              "value": "0",
              "text": "不可见"
            }],
            storeOptions: [],
            dosageformOptions: []
          },
          forms: {
            diseases: "",
            dialectical: "",
            department: "",
            storeId: 0,
            storeName: "",
            storeLogo: "",
            dosageFormId: 0,
            dosageForm: "",
            prescription: "",
            quantity: 1,
            frequency: "",
            administrationRoute: "",
            dailyDose: 1,
            medicalAdvice: "",
            visible: 0,
            billingMoney: 0.00,
            serviceMoney: 4,
            totalServiceMoney: 0,
            drugMoney: 0.000,
            totalDrugMoney: 0.000,
            totalMoney: 0.00
          },
          treatmentDrugs: []
        },

        created: function () {
          var $this = this;
          api.addEventListener({
            name: 'medicalAdvice'
          }, function (ret, err) {
            $this.forms.medicalAdvice = ret.value.content
          });
          api.addEventListener({
            name: 'broadcast-drugs'
          }, function (ret, err) {
            $this.treatmentDrugs = ret.value.allDrugs
            $this.forms.drugMoney = ret.value.drugMoney
            $this.defalultServiceMoneyFn($api.getStorage("emp").userId)
          });
          this.doctorFn($api.getStorage("emp").userId);
          this.userFn(api.pageParam.userId);
          this.patientFn(api.pageParam.consultationId);
          this.serviceMoneyFn($api.getStorage("emp").userId)
          this.defalultServiceMoneyFn($api.getStorage("emp").userId)
          this.dosageformList()

        },
        methods: {
          doctorFn: function (doctorUserId) {
            var $this = this
            // 请求医生个人信息数据
            get_ajax("doctor/verify/view", {
              userId: doctorUserId,
            }, function (res, err) {
              // alert(JSON.stringify(res))
              if (res.code == 2000) {
                $this.doctors.doctorAvatar = res.data.avatar ? IMAGE_HTTP + res.data.avatar : "";
                $this.doctors.doctorName = res.data.name ? res.data.name : "";
                $this.doctors.doctor = res.data.name ? res.data.name : "";
                $this.doctors.doctorUserId = res.data.userId ? res.data.userId : 0;
                $this.doctors.doctorJobtitle = res.data.jobtitle ? res.data.jobtitle : "";
                $this.doctors.department = res.data.department ? res.data.department : "";
              }
            })
          },
          userFn: function (userId) {
            var $this = this
            // 上级页面传递过来的用户参数
            get_ajax("ucenter/view", {
              userId: userId
            }, function (res, err) {
              if (res.code == 2000) {
                $this.users.avatar = res.data.avatar ? IMAGE_HTTP + res.data.avatar : "";
                $this.users.userId = res.data.userId ? res.data.userId : 0;
              }
            })
          },
          patientFn: function (consultationId) {
            var $this = this
            // 获得问诊单信息
            get_ajax("portal/consult/detail", {
              id: consultationId
            }, function (res, err) {
              /**此处有含有status 是会话状态，三种状态，0 待接诊，会话中(问诊中)，结束会话**/
              if (res.code == 2000 && res.data) {
                get_ajax("ucenter/patient/view", {
                  id: res.data.patientId
                }, function (res, err) {
                  if (res.code == 2000 && res.data) {
                    $this.patient = res.data
                    $this.patients.patientId = res.data.id ? res.data.id : 0;
                    $this.patients.userId = res.data.userId ? res.data.userId : 0;
                    $this.patients.name = res.data.name ? res.data.name : "";
                    $this.patients.sex = res.data.sex ? res.data.sex : 0;
                    $this.patients.phone = res.data.phone ? res.data.phone : "";
                    $this.patients.age = res.data.age ? res.data.age : 0;
                  } else {
                    alert("未查询到患者，请重试")
                    api.closeWin()
                  }
                })
              } else {
                alert("问诊单不存在，请先下单")
                api.closeWin()
              }
            })
          },
          //获得服务费选项
          serviceMoneyFn: function (userId) {
            var $this = this
            get_ajax("doctor/service-price", {
              doctorUserId: userId
            }, function (res, err) {
              if (res.code == 2000) {
                $this.iOptions.serviceOptions = res.data;
              }
            })
          },
          defalultServiceMoneyFn: function (userId) {
            var $this = this;
            get_ajax("doctor/default-service-price", {
              doctorUserId: userId,
              drugsPrice: String($this.forms.drugMoney)
            }, function (res, err) {
              // alert(JSON.stringify(res))
              if (res.code == 2000) {
                $this.forms.serviceMoney = res.data
                $this.forms.totalServiceMoney = $api.toThreeDecimal(Number($this.forms.quantity) * Number(res
                  .data));
                $this.forms.totalMoney = $api.toThreeDecimal(Number($this.forms.totalServiceMoney) + Number(
                    $this.forms.billingMoney) +
                  Number($this.forms.totalDrugMoney));
              }
            })
          },
          //选择给药路径
          chooseRouteFn: function (item) {
            this.forms.administrationRoute = item.value;
          },
          //选择给药频率
          chooseFrequencyFn: function (item) {
            this.forms.frequency = item.value;
          },
          chooseBillingFun: function (item) {
            if (typeof item == "object") {
              this.forms.billingMoney = item.value
            } else {
              this.forms.billingMoney = item
            }
          },
          openWinAdvice: function () {
            api.openWin({
              name: "medical_advice_win",
              url: "medical_advice_win.html",
              pageParam: {
                title: "医嘱",
                content: this.forms.medicalAdvice
              }
            })
          },
          openWinDrugs: function (flag) {
            api.openWin({
              name: "drugs_win",
              url: "drugs_win.html",
              pageParam: {
                title: "添加药材",
                allDrugs: this.treatmentDrugs,
                storeId: this.forms.storeId
              }
            })
          },
          openWinStore: function (item) {
            api.openWin({
              name: "pharmacy_detail_win",
              url: "widget://html/pharmacy_detail_win.html",
              pageParam: {
                id: item
              }
            })
          },
          chooseServiceFn: function (item) {
            this.forms.serviceMoney = item.value;
          },

          chooseVisibleFn: function (item) {
            this.forms.visible = item.value;
          },
          toThreeDecimal: function (item) {
            return $api.toThreeDecimal(item);
          },
          // 获取剂型列表
          dosageformList: function () {
            var $this = this;
            get_ajax("doctor/dosageform/list", {}, function (res, err) {
              if (res.code == 2000) {

                $this.iOptions.dosageformOptions = res.data
              }
            })
          },
          // 药材参数选择药房
          listStoreForDrugs: function (id, name, page) {
            var $this = this;
            post_ajax("store/service/page-price-list", {
              start: page,
              pagesize: 10,
              typeId: String(id),
              storeId: this.forms.storeId,
              storeDrugsDtos: this.treatmentDrugs,
            }, function (res, err) {
              // alert(JSON.stringify(res))
              if (res.code == 200) {
                $this.iOptions.storeOptions = res.data.data
                $this.forms.dosageFormId = id
                $this.forms.dosageForm = name
                $this.totalCount = res.data.totalCount
              } else {
                toast("没有药房！")
                return;
              }
            })

          },
          //选择药房
          chooseStore: function (item) {
            this.forms.storeId = item.id;
            this.forms.storeName = item.name
            this.forms.storeLogo = item.image ? IMAGE_HTTP + item.image : "../../image/logo.png"
          },
          // 药房列表
          listStoreByDosage: function (item) {
            var $this = this;
            get_ajax("doctor/store/list/page/dosage", {
              start: 1,
              pagesize: 2,
              dosageId: item.id,
            }, function (res, err) {
              if (res.code == 2000) {
                $this.iOptions.storeOptions = res.data.data
                $this.forms.dosageFormId = item.id
                $this.forms.dosageForm = item.name
                $this.totalCount = res.data.totalCount
              } else {
                toast("没有药房！")
              }
            })

          },
          confirmFn: function () {
            if (!this.forms.diseases) {
              toast("请输入辨病")
              return;
            }
            if (!this.forms.dialectical) {
              toast("请输入辩证")
              return;
            }
            if (!this.forms.dosageFormId) {
              toast("请选择剂型")
              return
            }
            if (!this.forms.prescription) {
              toast("请输入处方药材")
              return;
            }
            if (!this.forms.quantity) {
              toast("请输入开药量")
              return;
            }
            if (!this.forms.storeId) {
              toast("请选择药房")
              return;
            }
            if (!this.forms.dailyDose) {
              toast("请输入每日药量")
              return;
            }
            if (!this.forms.frequency) {
              toast("请输入给药频率")
              return;
            }
            if (!this.forms.medicalAdvice) {
              toast("请输入相关医嘱")
              return;
            }
            var data = {
              doctorId: String($api.getStorage("emp").userId), // 医生账号id
              doctorName: this.doctors.doctorName, // 医生姓名
              doctor: this.doctors.doctor, // 医生姓名
              department: this.doctors.department, // 医生科室
              patientId: String(this.patients.patientId), // 档案id
              userId: this.patients.userId, // 选择的患者id
              userName: String(this.patients.name), // 患者姓名
              sex: this.patients.sex, // 患者性别
              age: this.patients.age, // 患者年龄
              diseases: this.forms.diseases, // 病名
              dialectical: this.forms.dialectical, // 病症
              storeId: this.forms.storeId, // 药房id
              storeName: this.forms.storeName, // 药房名称
              storeLogo: this.forms.storeLogo, // 药房logo
              dosageFormId: String(this.forms.dosageFormId), // 剂型id
              dosageForm: this.forms.dosageForm,
              prescription: this.forms.prescription, // 处方药材
              administrationRoute: this.forms.administrationRoute, //用药方法
              quantity: this.forms.quantity, // 总量多少帖
              dailyDose: this.forms.dailyDose, //每日用药量
              frequency: this.forms.frequency, //给药频率
              medicalAdvice: this.forms.medicalAdvice, // 用法详述
              visible: this.forms.visible, // 购药前处方是否可见
              billingMoney: this.forms.billingMoney, // 诊费诊金
              serviceMoney: this.forms.serviceMoney, // 服务费
              drugMoney: this.forms.drugMoney, // 药价
              remark: '无备注', // 备注
              prescribeDrugs: this.treatmentDrugs, // 处方药材
              source: "online"
            }
            var $this = this;
            post_ajax("doctor/prescribe/save", data, function (res, err) {
              if (res.code == 2000 && res.data) {
                // alert(JSON.stringify(res.data))
                var now = new Date();
                var year = now.getFullYear(); //得到年份
                var month = now.getMonth() + 1; //得到月份
                var date = now.getDate(); //得到日期
                var hour = now.getHours(); //得到小时数
                var minute = now.getMinutes(); //得到分钟数
                api.sendEvent({
                  name: "card",
                  extra: {
                    title: $this.forms.administrationRoute,
                    time: year + "-" + month + "-" + date + "  " + hour + ":" + minute,
                    userName: $this.patients.name,
                    userAge: $this.patients.age,
                    userSex: $this.patients.sex,
                    diseases: $this.forms.diseases,
                    dialectical: $this.forms.dialectical,
                    patientId: res.data
                  }
                });
                toast("开方成功");
                setTimeout(function () {
                  api.closeWin()
                }, 500);
                return
              } else {
                toast("开方失败");
                return
              }
            });
          } //endconfirm

        },
        watch: {
          "forms.billingMoney": function (val) {
            var that = this
            that.forms.totalMoney = Number(val) +
              Number(that.forms.totalDrugMoney) +
              Number(that.forms.totalServiceMoney)
            that.forms.totalMoney = $api.toThreeDecimal(that.forms.totalMoney)
          },
          "forms.serviceMoney": function (val) {
            var that = this
            that.forms.totalServiceMoney = $api.toThreeDecimal(Number(val) * Number(that.forms.quantity))

            that.forms.totalMoney = Number(that.forms.billingMoney) +
              Number(that.forms.totalDrugMoney) +
              Number(that.forms.totalServiceMoney);
            that.forms.totalMoney = $api.toThreeDecimal(that.forms.totalMoney)
          },
          "forms.drugMoney": function (val) {
            var that = this
            that.forms.totalDrugMoney = $api.toThreeDecimal(Number(val) * Number(that.forms.quantity))
            that.forms.totalMoney = Number(that.forms.billingMoney) + Number(that.forms.totalDrugMoney) + Number(
              that.forms.totalServiceMoney)
            that.forms.totalMoney = $api.toThreeDecimal(that.forms.totalMoney)
          },
          "forms.quantity": function (val) {
            var that = this
            that.forms.totalDrugMoney = $api.toThreeDecimal(Number(that.forms.drugMoney) * Number(val))
            that.forms.totalServiceMoney = Math.round(Number(val) * Number(that.forms.serviceMoney))
            that.forms.totalMoney = Number(that.forms.billingMoney) + Number(that.forms.totalServiceMoney) +
              (Number(that.forms.drugMoney) * Number(val))
            that.forms.totalMoney = $api.toThreeDecimal(that.forms.totalMoney)
          }, //endquantity
          treatmentDrugs: function () {
            var that = this
            that.forms.drugMoney = 0;
            for (i in that.treatmentDrugs) {
              var item = that.treatmentDrugs[i].name + that.treatmentDrugs[i].quantity + that.treatmentDrugs[i]
                .unit;
              that.forms.prescription += item + ","
              that.forms.drugMoney += (Number(that.treatmentDrugs[i].salePrice) * Number(that.treatmentDrugs[i]
                .quantity));
            }
            that.forms.drugMoney = $api.toThreeDecimal(that.forms.drugMoney)
            that.forms.totalMoney = $api.toThreeDecimal(Number(that.forms.drugMoney) * that.forms.quantity)
            that.forms.prescription = that.forms.prescription.slice(0, that.forms.prescription.length - 1);
          }
        } //endwatch

      });
    }
  </script>
</body>

</html>
